package cn.edu.fzu.delivery.task;

import cn.edu.fzu.delivery.domain.entity.Courier;
import cn.edu.fzu.delivery.domain.entity.CourierDelivery;
import cn.edu.fzu.delivery.domain.enums.CourierStatusEnum;
import cn.edu.fzu.delivery.handler.DeliveryHandler;
import cn.edu.fzu.delivery.handler.DeliverySession;
import cn.edu.fzu.delivery.helper.EmailHelper;
import cn.edu.fzu.delivery.service.CourierDeliveryService;
import cn.edu.fzu.delivery.service.CourierService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ExecutorService;

/**
 * 快递派件定时任务
 * 
 * @author fangxin
 * @date 2022/11/9
 */
@Component
public class DeliveryTask {

    private static final Logger log = LoggerFactory.getLogger(DeliveryTask.class);

    private static final String    EMAIL_TITLE   = "取件失败通知";
    private static final String    EMAIL_CONTENT = "亲爱的顾客，很抱歉通知您，您的快递取件失败。\r\n您可以选择取消当前快递。获取重新提交。\r\n失败原因为：";
    @Resource
    private CourierService         courierService;
    @Resource
    private CourierDeliveryService courierDeliveryService;
    @Resource
    private List<DeliveryHandler>  deliveryHandlers;
    @Resource
    private ExecutorService        threadPool;
    @Resource
    private EmailHelper            emailHelper;

    @Scheduled(cron = "0 0/5 * * * ?")
    public void run() {
        log.info("DeliveryTask run");
        //查询出所有待取件的快递
        List<Courier> couriers = courierService.listByStatus(CourierStatusEnum.UNCOLLECTED);
        if (CollectionUtils.isEmpty(couriers)) {
            return;
        }
        for (Courier courier : couriers) {
            List<CourierDelivery> list = courierDeliveryService.list(null, courier.getCourierId(), null, null, null,null);
            if (!CollectionUtils.isEmpty(list)) {
                //已经有快递员了则跳过
                continue;
            }
            threadPool.submit(new Runnable() {
                @Override
                public void run() {

                    DeliverySession session = DeliverySession.build(courier);
                    for (DeliveryHandler handler : deliveryHandlers) {
                        if (!handler.process(session)) {
                            //出错，则通知顾客
                            emailHelper.sendMail(courier.getSender().getEmail(), EMAIL_TITLE,
                                    EMAIL_CONTENT + session.getError().getDesc());
                            courierService.update(courier.getCourierId(), null, CourierStatusEnum.ERROR, null, null,
                                    false);
                            break;
                        }
                    }
                }
            });
        }
    }
}
